<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2022-10-19 11:40:43
 * @LastEditors: Sam
 * @LastEditTime: 2022-10-19 14:52:12
 */

namespace app\commom\api;

use think\facade\Db;
use think\facade\Env;
use app\common\api\QyWeChat;


class Push extends ApiBase
{

	/*****
     *企业微信消息推送
     */
    public function auth(){

        include_once ROOT_PATH .'extend/callback/WXBizMsgCrypt.php';

		$get = !empty($_GET)?$_GET:[];

		$xml = file_get_contents('php://input');
		
		$encryptData  = xmltoarray(file_get_contents('php://input'));

		//企业微信配置 encodingAesKey
		$encodingAesKey = app()->env->get('qy_wechat_aeskey');

		//企业微信配置 token
		$token = app()->env->get('qy_wechat_token');

		//企业微信开发者ID
		$corpId = app()->env->get('qy_wechat_corpid');

		//企业微信secret
		$corpsecret = app()->env->get('qy_wechat_corpsecret');

		$sReqMsgSig     = !empty($get['msg_signature'])?$get['msg_signature']:'';
		
		$sReqTimeStamp  = !empty($get['timestamp'])?$get['timestamp']:'';
	
		$sReqNonce      = !empty($get['nonce'])?$get['nonce']:'';

		$sVerifyEchoStr = !empty($get['echostr'])?$get['echostr']:'';

		if(!empty($get) && !empty($encryptData)){


			$sMsg    = "";  // 解析之后的明文
		
			$wxcpt   =  new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
		
			$errCode = $wxcpt->DecryptMsg($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $xml, $sMsg);
		
			if ($errCode == 0) {
				// 解密成功，sMsg即为xml格式的明文
			   $val = xmltoarray($sMsg);
		
			   if(!empty($val['ChangeType']) && ($val['ChangeType']=='add_external_contact' || $val['ChangeType']=='del_follow_user') && !empty($val['UserID'])){
		
				    $ExternalUserID = $val['ExternalUserID'];

		
			   }

				$QyWeChat = new QyWeChat($corpId, $corpsecret);
				
				$unionid = $QyWeChat->get_contact($ExternalUserID);

				if($unionid){
					//添加企业微信客服
					if($val['ChangeType']=='add_external_contact'){

					}
					//企业微信客服删除客户
					if($val['ChangeType']=='del_follow_user'){

					}
				}
		  
			} else {
	
				json_response($errCode, '解密失败');
			}
			
		}else{

			$wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
			$errCode = $wxcpt->VerifyURL($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $sVerifyEchoStr, $sEchoStr);

			if ($errCode == 0) {
				return $sEchoStr;
			} else {
				json_response($errCode, 'URL错误');
			}
		}


	}
}